<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

    /**
     * 处理插件钩子
     *
     * @param string $hook 钩子名称
     * @param mixed $params 传入参数
     * @return void
     */
    function hook($hook, $params = [])
    {
       $a = \think\Hook::listen($hook, $params);
       var_dump($a);
    }

    /**
     * 组合多维数组
     *
     * @return array
     */
    function unlimitedForLayer ($cate, $name = 'child', $parent_id = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $v[$name] = unlimitedForLayer($cate, $name, $v['id']);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    /**
     * 组合一维数组
     *
     * @return array
     */
    function unlimitedForLevel ($cate, $html = '--', $parent_id = 0, $level = 0)
    {
        $arr = array();
        foreach ($cate as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['level'] = $level + 1;
                $v['html']  = str_repeat($html, $level);
                $arr[] = $v;
                $arr = array_merge($arr, unlimitedForLevel($cate, $html, $v['id'], $level + 1));
            }
        }
        return $arr;
    }

    /**
     * 组合一维数组
     *
     * @return array
     */
    function list_for_level($list, $html = '--', $pid = 0, $level = 0)
    {
        $arr = array();
        foreach ($list as $k => $v) {
            if ($v['parent_id'] == $pid) {
                $v['level'] = $level + 1;
                $v['html']  = str_repeat($html, $level);
                $arr[] = $v;
                $arr = array_merge($arr, list_for_level($list, $html, $v['id'], $level + 1));
            }
        }
        return $arr;
    }

    /**
     * 传递一个子分类ID返回所有的父级分类
     *
     * @return array
     */
    function getParents ($cate, $id)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['id'] == $id) {
                $arr[] = $v;
                $arr = array_merge(getParents($cate, $v['parent_id']), $arr); 
            }
        }
        return $arr;
    }

    /**
     * 传递一个父级分类ID返回所有子分类ID
     *
     * @return array
     */
    function getChildsId ($cate, $parent_id)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $arr[] = $v['id'];
                $arr = array_merge($arr, getChildsId($cate, $v['id']));
            }
        }
        return $arr;
    }

    /**
     * 传递一个父级分类ID返回所有子分类
     *
     * @return array
     */
    function getChilds ($cate, $parent_id)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $arr[] = $v;
                $arr = array_merge($arr, getChilds($cate, $v['id']));
            }
        }
        return $arr;
    }


    /**
     * 字符串截取，支持中文和其他编码
     *
     * @static
     * @access public
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $charset 编码格式
     * @param string $suffix 截断显示字符
     * @return string
     */
    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
            if(false === $slice) {
                $slice = '';
            }
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        return $suffix ? $slice.'...' : $slice;
    }

    /**
     * 把返回的数据集转换成Tree
     *
     * @param array $list 要转换的数据集
     * @return array
     */
    function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
        // 创建Tree
        $tree = array();
        if(is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    /**
     * 生成验证码URL
     *
     * @param  $id
     * @return string
     */
    function captcha_src($id = "")
    {
        return \think\Url::build('api/captcha/index' . ($id ? "/{$id}" : ''));
    }

    /**
     * 生成验证码图片标签
     *
     * @param $id
     * @return mixed
     */
    function captcha_img($id = "")
    {
        return '<img src="' . captcha_src($id) . '" alt="点击更换" onclick="this.src=\''.captcha_src().'?rand=\'+Math.random();" style="cursor:pointer"/>';
    }

    /**
     * 校验验证码
     *
     * @param        $value
     * @param string $id
     * @param array  $config
     * @return bool
     */
    function captcha_check($value, $id = "", $config = [])
    {
        $captcha = new \verify\Captcha($config);
        return $captcha->check($value, $id);
    }

    /**
     * 检测用户是否登录
     *
     * @return inf 0 未登录，大于0 当前登录用户ID
     */
    function is_login()
    {
        $user = session('user_auth');
        if (empty($user)) {
            return 0;
        } else {
            $model = new \app\common\logic\Passport();
            return session('user_auth_sign') == $model->sign($user) ? $user['uid'] : 0;
        }
    }

    /**
     * 获取网站地址 传输协议://域名/目录
     *
     * params $protocol string 传输协议
     * @return string
     */
    function getDomain($protocol = '')
    {
        // 传输协议
        if (empty($protocol)) {
            $protocol = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http';
        }

        // 返回当前文件名目录
        $ccript = dirname($_SERVER['SCRIPT_NAME']);

        // 判断是目录还是跟目录 如果为根目录 返回值为斜杠
        if (strlen($ccript) > 1) {
            $domain = $protocol . "://". $_SERVER['HTTP_HOST'] . $ccript . DS;
        } else {
            $domain = $protocol . "://". $_SERVER['HTTP_HOST'] . DS;
        }

        // 替换为通用斜杠
        return  str_replace('\\', '/', $domain);
    }

    /*
     * 生成图片绝对路径
     *
     * @params $image_url string 图片路径
     * @return string 协议://域名/目录/图片地址
        例如：(https://www.kitesky.com/v1/upload/image/20170423/xxx.jpg)
    */
    function buildImageUrl($image_url)
    {
        return str_replace("\\", "/", getDomain() . $image_url);
    }

    /*
     * 默认图片
     *
     * @return string 协议://域名/目录/图片地址
    */
    function defaultImageUrl()
    {
        $image_url = 'static/img/nopic.jpg';
        return buildImageUrl($image_url);
    }

    /**
     * 判断是否开启验证码
     *
     * @return boolean
    */
    function is_captcha($num = 0)
    {
        $option = \app\common\model\Config::getValue('open_captcha');
        return in_array($num, json_decode($option, true)) ? true : false;
    }

    /**
     * 获取客户端IP地址
     *
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
     */
    function get_client_ip($type = 0, $adv = false) {
        $type      = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) {
            return $ip[$type];
        }

        // 高级模式获取
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }

                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    /**
     * 提取内容中图片
     *
     * @param $content string 内容
     * @param $num int 提取第几张
     * @param array|string
     */
    function pickImage($content, $num = '') {
        
        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.bmp]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $content, $matchs); 
        $tempList = array_unique($matchs[1]);

        // 遍历生成绝对路径
        $list = array();
        if (!empty($tempList)) {
            foreach ($tempList as $v) {
                array_push($list, buildImageUrl(ltrim($v, '\/')));
            }

            // 如果指定提取第X张
            if (is_numeric($num)) {
                return $list[$num];
            }
        }

        return $list;
    }

    /**
     * 友好时间格式化
     *
     * @params $time string 日期
     * @params $format string 需要格式化的日期格式
     * @return string
     */
    function format_date($time, $format = '')
    {
        $time = strtotime($time);

        // 如果传入格式 按照格式进行格式化
        if (!empty($format)) {
            return date('Y-m-d', $time);
        }

        // 默认为友好时间格式
        $etime = time() - $time;
        if ($etime < 1) {
            return '刚刚';
        }

        $interval = array (
            12 * 30 * 24 * 60 * 60 => '年前',
            30 * 24 * 60 * 60      => '个月前',
            7 * 24 * 60 * 60       => '周前',
            24 * 60 * 60           => '天前',
            60 * 60                => '小时前',
            60                     => '分钟前',
            1                      => '秒前'
        );

        foreach ($interval as $secs => $str) {
            $d = $etime / $secs;
            if ($d >= 1) {
                $r = round($d);
                return $r . $str;
            }
        }
    }

    function bread_crumb()
    {
        
    }